<script lang="ts" setup>
import { computed, onUnmounted, ref } from 'vue'
import { ipcRenderer, type IpcRendererEvent } from '@/utils/electron';
import EmailInput from '@/components/Inputs/EmailInput.vue'
import { UserLoginEvent } from '@/enums/event'
import { LOCAL_KEY_USER_LOGIN_EMAIL } from '@/enums/keys'

type LogonResponse = {
  message: string,
  token?: string
}

const email = ref('');                      // 输入框密码值
const password = ref('');                   // 输入框密码值
const autoLogin = ref<boolean>(true);       // 自动登陆
const savePassword = ref<boolean>(false);   // 记住密码
const eyeOpen = ref<boolean>(false);        // 表示输入框眼睛睁开状态
const passwordWarnText = ref('');           // 错误提示信息


const _storage_email = localStorage.getItem(LOCAL_KEY_USER_LOGIN_EMAIL)
if (_storage_email) { email.value = _storage_email; }

function isEmail(email: string): boolean {
  return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email);
}

function ipcStateSynchronization<V>(eventName: string, listener: (value: V) => void) {
  ipcRenderer.send('subscribe', eventName);
  // 监听来自主进程的 "exampleEvent" 事件
  ipcRenderer.on(UserLoginEvent, (event, data: V) => {
    listener(data)
  });
}
// 登陆成功后同步状态
ipcStateSynchronization<{ token: string }>(UserLoginEvent, (value) => {
  // 当收到 "exampleEvent" 事件时，处理事件数据
  console.log(`收到事件 login-success-event 的数据: ${JSON.stringify(value)}`);
})

// 密码输入框类型
const inputType = computed(() => { return eyeOpen.value ? 'text' : 'password' })

// 图标名
const eyeIconName = computed(() => { return eyeOpen.value ? 'eyes-open' : 'eyes-close' })



// 处理登陆请求结果的监听器
function handleLoginReply(event: IpcRendererEvent, response: LogonResponse) {
  if (response.token) {
    // 将登陆成功的事件发布给所有的进程
    // console.log('发布 login-success-event 事件给所有进程');
    ipcRenderer.send('publish', UserLoginEvent, { token: response.token });
  }
  else {
    passwordWarnText.value = '用户名或者密码错误';
  }
}

ipcRenderer.on('user-login-reply', handleLoginReply);

// 移除监听器
onUnmounted(() => { ipcRenderer.removeListener('user-login-reply', handleLoginReply); });


function login() {
  if (email.value === '') {
    passwordWarnText.value = '邮箱不能为空'
  }
  else if (!isEmail(email.value)) {
    passwordWarnText.value = '邮箱格式不正确'
  }
  else if (password.value === '') {
    passwordWarnText.value = '密码不能为空'
  } else {
    passwordWarnText.value = '';
    localStorage.setItem(LOCAL_KEY_USER_LOGIN_EMAIL, email.value)
    ipcRenderer.send('user-login', email.value, password.value);
  }
}

</script>

<template>
  <div class="login-container">
    <h1>登 陆</h1>
    <form>
      <EmailInput v-model="email" />
      <div class="password-group">
        <input :type="inputType" v-model="password" @keydown.enter="login" placeholder="请输入密码" />
        <jc-icon class="eye-icon" @click="($event: MouseEvent) => { eyeOpen = !eyeOpen }" :name="eyeIconName" />
      </div>
    </form>

    <p class="input-warnnings">{{ passwordWarnText }}</p>
    <div class="line">
      <!-- 保存密码选项 -->
      <div class="input-box">
        <input type="checkbox" v-model="savePassword" id="save-password" name="savepwsd" />
        <label for="save-password">
          <a class="text-label">记住密码</a>
        </label>
      </div>
      <!-- 自动登陆选项 -->
      <div class="input-box">
        <input type="checkbox" v-model="autoLogin" id="auto-login" name="autologin" />
        <label for="auto-login">
          <a class="text-label">自动登陆</a>
        </label>
      </div>
    </div>
    <!-- 登陆按钮 -->
    <button @click="$event => login()" class="login">登 陆</button>
    <a class="text-bt ">忘记密码？</a>
  </div>
</template>

<style lang="scss" scoped>
// @import url(../base.scss);
$inline-text-size: 15px;
$bg-color: #f09f4d;

.input-box {
  margin: 0;
  padding: 0;

  input {
    width: $inline-text-size;
    height: $inline-text-size;
  }

  label {
    font-size: $inline-text-size;
    padding-top: 0;
    padding-left: 6px;
    cursor: pointer;

    a.text-label {
      font-size: $inline-text-size;
      color: #ffffff;
    }
  }
}

p.input-warnnings {
  font-size: 12px;
  text-align: left;
  color: red;
}

.line {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  flex-direction: row;
  justify-content: space-between;
}

.login-container {
  width: 100%;
  height: 100%;
  margin-top: 32%;
  padding: 6px;

  .password-group {
    position: relative;

    .eye-icon {
      font-size: 19px;
      position: absolute;
      top: 16px;
      right: 9px;
      cursor: pointer;
      color: rgb(152, 152, 152);

      &:hover {
        color: #000000;
      }

      &:active {
        color: #f09f4d;
      }
    }
  }


  /* background-color: aliceblue; */
  h1 {
    padding: 16px;
    color: rgb(255, 234, 208);
  }

  button.login {
    width: 100%;
    font-size: 19px;
    background-color: $bg-color;
  }
}

.text-bt {
  padding: 9px;
}
</style>
